package com.freely.dao.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.alibaba.fastjson.JSONObject;
import com.freely.dao.MessageDao;
import com.freely.domain.Message;

public class MessageDaoImpl extends HibernateDaoSupport implements MessageDao {

	@Override
	public List<Message> findByCondition(DetachedCriteria criteria) {
		List<Message> result = (List<Message>) this.getHibernateTemplate().findByCriteria(criteria);
		if (result == null || result.size() <= 0) {
			return null;
		}
		return result;
	}

	@Override
	public int update(JSONObject modifyObj, JSONObject conditionObj) {
		// 配置更新语句
		if (modifyObj == null || modifyObj.size() == 0) {
			return -1;
		}
		StringBuilder sb = new StringBuilder("update Message set ");
		Set<String> modifyKey = modifyObj.keySet();
		for (String key : modifyKey) {
			sb.append(key + " = :" + key + " , ");
		}
		sb.delete(sb.length() - 2, sb.length());
		if (conditionObj != null && conditionObj.size() > 0) {
			sb.append("where ");
			Set<String> conditionKey = conditionObj.keySet();
			for (String key : conditionKey) {
				sb.append(key + " = :" + key + " and ");
			}
			sb.delete(sb.length() - 4, sb.length());
			modifyObj.putAll(conditionObj);
		}
		System.out.println("[" + sb.toString() + "]");
		// 添加参数
		Session session = this.currentSession();
		Query query = session.createQuery(sb.toString());
		Set<Entry<String, Object>> set = modifyObj.entrySet();
		Iterator<Entry<String, Object>> iterator = set.iterator();
		while (iterator.hasNext()) {
			Entry<String, Object> entry = iterator.next();
			query.setParameter(entry.getKey(), entry.getValue());
		}
		return query.executeUpdate();
	}

}
